//
//  JSTCommentViewController.m
//  KYKJPackDemo
//
//  Created by 01 on 17/5/16.
//  Copyright © 2017年 ???. All rights reserved.
//

#import "JSTCommentViewController.h"
#import "JSTCommonCenterView.h"
#import "JSTCommonHeaderView.h"
#import "JSTInterestcircleDataModel.h"
#import "JSTCommentCell.h"
#import "JSTCommentFootView.h"
#import "JSTUserInfoViewController.h"
#import "JSTPublishViewController.h"

@interface JSTCommentViewController ()<UITableViewDelegate, UITableViewDataSource, JSTCommonHeaderViewDelegate, JSTCommentFootViewDelegate, JSTCommentCellDelegate>
{
    NSIndexPath *myIndexPath;
    
    // 是否允许评论
    BOOL allowComment;
}

@property (nonatomic, assign) NSInteger                         currePage;

@property (nonatomic, strong) NSMutableArray                    *dataFramArray;

@property (nonatomic, strong) JSTCommonCenterView               *inPutBar; //输入条

@property (nonatomic, strong) NSMutableArray                    *dataSource;

@property (nonatomic, strong) UIButton                          *sendBtn;

@property (nonatomic, assign) BOOL                              btnIndicates;

@property (nonatomic, strong) UITableView                       *tabView;

@property (nonatomic, strong) JSTCommonHeaderView               *headerView;

@property (nonatomic, strong) JSTCommentFootView                *footerVeiw;

@property (nonatomic, strong) JSTInterestcircleDataModel        *dataModel;

@property (nonatomic, strong) JSTDynamicDetailsCommentModel     *commentModel;

@property (nonatomic, strong) JSTDynamicDetailsPraiseModel      *praiseModel;

@property (nonatomic, strong) NSMutableArray                    *commentData;

@property (nonatomic, strong) NSMutableArray                    *praiseData;

@property (nonatomic, assign) BOOL                              isComment;

@property (nonatomic, strong) UIView                            *faildView;

@property (nonatomic, strong) UIView                            *listFaildView;

@property (nonatomic, strong) UIImageView                       *faildImageView;

@property (nonatomic, strong) NSIndexPath                       *longPressIndexPath;

@property (nonatomic, strong) NSString                          *currentUserId;

@end

@implementation JSTCommentViewController

#pragma mark - lifecycle
- (void)viewDidLoad
{
    [super viewDidLoad];

    // 0.初始化所有的子控件
    [self setUpAllSubViews];
    
    // 1.设置基本属性
    [self setUpAttris];
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    // 2.获取评论的数据
    [self setUpCommentData];
}

#pragma mark - 设置标题&基础属性
- (void)setUpAttris
{
    self.title = NSLocalizedString(@"详情", nil);
    
    _isComment = YES;
    
    KYLog(@"----- userModel = %@", [JSTSystemInfo userDict]);
    _currentUserId = [[JSTSystemInfo userDict] valueForKey:@"uid"];
}

#pragma mark - 初始化所有的子控件
- (void)setUpAllSubViews
{
    [self.view addSubview:self.tabView];
    [self.tabView addSubview:self.listFaildView];
    
    self.footerVeiw.layer.borderWidth = 0.75;
    self.footerVeiw.layer.borderColor = [UIColor lightGrayColor].CGColor;
    
    [self.view addSubview:self.footerVeiw];
    [self.view addSubview:self.inPutBar];
}

#pragma mark - 获取详情数据
- (void)setUpCommentData
{
    [JSTNewServer requestDynamicDetails:_dynamicId success:^(NSDictionary *dataDic) {
        
        // 0.移除加载&失败的展示
        [self.tabView headerEndRefreshing];
        [self.faildView removeFromSuperview];
        
        // 1.处理数据
        [self handleData:dataDic];
    } error:^(NSString *errStr) {
        [self.tabView headerEndRefreshing];
        [self.view addSubview:self.faildView];
    }];
}

- (void)handleData:(NSDictionary *)dataDic
{
    KYLog(@"dataDic = %@", dataDic);
    
    // 1.评论&点赞的数组
    _commentData = [NSMutableArray array];
    _praiseData = [NSMutableArray array];
    
    // 2.数据结构
    NSDictionary *commentDic = [dataDic valueForKey:@"discuss"];
    NSDictionary *praiseDic = [dataDic valueForKey:@"zan"];
    NSDictionary *headerDic = [dataDic valueForKey:@"msg_info"];
    
    // 3.评论的数据
    NSArray *commentArr = [commentDic valueForKey:@"data"];
    if (!IsArrEmpty(commentArr)) {
        [commentArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
             JSTDynamicDetailsCommentModel *commentModel = [[JSTDynamicDetailsCommentModel alloc] init];
             commentModel.commentId = [KYHandleDataTool getStr:[obj valueForKey:@"id"]];
             commentModel.iconUrl = [KYHandleDataTool getStr:[obj valueForKey:@"icon"]];
             commentModel.userNick = [KYHandleDataTool getStr:[obj valueForKey:@"name"]];
             commentModel.contentText = [KYHandleDataTool getStr:[obj valueForKey:@"content"]];
             commentModel.timeStr = [KYHandleDataTool getStr:[obj valueForKey:@"addtime"]];
             commentModel.replyName = [KYHandleDataTool getStr:[obj valueForKey:@"h_name"]];
             commentModel.replyId = [KYHandleDataTool getStr:[obj valueForKey:@"h_uid"]];
             commentModel.userId = [KYHandleDataTool getStr:[obj valueForKey:@"apuid"]];
             [_commentData addObject:commentModel];
         }];
    }
    
    // 4.点赞的数据
    NSArray *praiseArr = [praiseDic valueForKey:@"data"];
    if (!IsArrEmpty(praiseArr)) {
        [praiseArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
             JSTDynamicDetailsPraiseModel *praiseModel = [[JSTDynamicDetailsPraiseModel alloc] init];
             praiseModel.praiseId = [KYHandleDataTool getStr:[obj valueForKey:@"zanid"]];
             praiseModel.userNick = [KYHandleDataTool getStr:[obj valueForKey:@"nickname"]];
             praiseModel.iconUrl = [KYHandleDataTool getStr:[obj valueForKey:@"icon"]];
             praiseModel.timeStr = [KYHandleDataTool getStr:[obj valueForKey:@"addtime"]];
             praiseModel.userId = [KYHandleDataTool getStr:[obj valueForKey:@"id"]];
             [_praiseData addObject:praiseModel];
         }];
    }
    
    _dataModel = [[JSTInterestcircleDataModel alloc] init];
    _dataModel.commentNumber = [KYHandleDataTool getStr:[commentDic valueForKey:@"count"]];
    _dataModel.pointPraise = [KYHandleDataTool getStr:[praiseDic valueForKey:@"count"]];
    _dataModel.dynamicId = [KYHandleDataTool getStr:[headerDic valueForKey:@"id"]];
    _dataModel.iconImgUrl = [KYHandleDataTool getStr:[headerDic valueForKey:@"icon"]];
    _dataModel.userName = [KYHandleDataTool getStr:[headerDic valueForKey:@"nickname"]];
    _dataModel.contentImgUrlArr = [headerDic valueForKey:@"imglist"];
    _dataModel.contentText = [KYHandleDataTool getStr:[headerDic valueForKey:@"content"]];
    _dataModel.timeText = [KYHandleDataTool getStr:[headerDic valueForKey:@"addtime"]];
    _dataModel.praiseStatus = [KYHandleDataTool getStr:[dataDic valueForKey:@"is_zan"]].boolValue;
    _dataModel.userId = [KYHandleDataTool getStr:[headerDic valueForKey:@"apuid"]];
    
    // 5.判断可评论性
    self.headerView.isCommentList = _isComment;
    
    // 6.根据数据头部子控件&设置frame
    [self.headerView createContent:_dataModel];
    self.headerView.frame = CGRectMake(0, 0, kScreenWidth, self.headerView.headerHight);
    self.tabView.tableHeaderView = self.headerView;
    [self.tabView reloadData];
    
    // 7.设置底部的toolBar
    [self.footerVeiw createContent:_dataModel.praiseStatus];
    
    // 8.根据评论&点赞个数选择和隐藏加载图片
    if (_commentData.count == 0 && _isComment) {
        _listFaildView.frame = CGRectMake(0, CGRectGetMaxY(self.headerView.frame) + kCurrentScreenWidth(30), kScreenWidth, kCurrentScreenWidth(150));
        self.faildImageView.image = [UIImage imageNamed:@"state_comments_bg"];
        self.listFaildView.hidden = NO;
        return;
    }
    
    if (_praiseData.count == 0 && !_isComment) {
        _listFaildView.frame = CGRectMake(0, CGRectGetMaxY(self.headerView.frame) + kCurrentScreenWidth(30), kScreenWidth, kCurrentScreenWidth(150));
        self.faildImageView.image = [UIImage imageNamed:@"state_Thumbup_bg"];
        return;
    }
    
    self.listFaildView.hidden = YES;
}

#pragma mark - 数据源&代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_isComment) {
        return _commentData.count;
    } else {
        return _praiseData.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JSTCommentCell *cell;
    if (!cell) {
        cell = [[JSTCommentCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"jstCommentCell"];
    }
    if (_isComment) {
        [cell createCommentContent:[_commentData safeObjectAtIndex:indexPath.row]];
    } else {
        [cell createPraiseContent:[_praiseData safeObjectAtIndex:indexPath.row]];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.delegate = self;
    
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(cellLongpress:)];
    [cell addGestureRecognizer:longPress];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JSTCommentCell *cell = (JSTCommentCell *)[self tableView:self.tabView cellForRowAtIndexPath:indexPath];
    return cell.cellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_isComment) {
        if (![KYUserAccountTool shareUserData].token) {
            KYLoginController *loginVc = [[KYLoginController alloc] init];
            KYNavigationController *nav = [[KYNavigationController alloc] initWithRootViewController:loginVc];
            [self presentViewController:nav animated:YES completion:nil];
            return;
        }
        JSTDynamicDetailsCommentModel *model = [_commentData safeObjectAtIndex:indexPath.row];
        KYLog(@"currentUserId = %@,model.userId = %@", _currentUserId, model.userId);
        if ([_currentUserId isEqualToString:model.userId]) {
            return;
        }
        JSTPublishViewController *publishViewController = [[JSTPublishViewController alloc] init];
        publishViewController.dynamicId = _dataModel.dynamicId;
        publishViewController.personId = model.userId;
        publishViewController.personName = model.userNick;
        [self.navigationController pushViewController:publishViewController animated:YES];
    } else {
        JSTDynamicDetailsPraiseModel *model = [[JSTDynamicDetailsPraiseModel alloc] init];
        model = [_praiseData safeObjectAtIndex:indexPath.row];
        [self changePersonPage:model.praiseId];
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

#pragma mark - 长按cell方法
- (void)cellLongpress:(UILongPressGestureRecognizer *)longPress
{
    if (_isComment) {
        if (longPress.state == UIGestureRecognizerStateBegan) {
            CGPoint location = [longPress locationInView:self.tabView];
            _longPressIndexPath = [self.tabView indexPathForRowAtPoint:location];
            JSTCommentCell *cell = (JSTCommentCell *)longPress.view;
            
            [cell becomeFirstResponder];
            
            UIMenuItem *deleteItem = [[UIMenuItem alloc] initWithTitle:@"删除" action:@selector(deleteCurrentComment:)];
            UIMenuItem *replyItem = [[UIMenuItem alloc] initWithTitle:@"回复" action:@selector(replyCurrentComment:)];
            UIMenuController *menu = [UIMenuController sharedMenuController];
            [menu setTargetRect:cell.frame inView:self.tabView];
            
            JSTDynamicDetailsCommentModel *model = [_commentData safeObjectAtIndex:_longPressIndexPath.row];
            
            KYLog(@"currentUserId = %@,model.userId = %@", _currentUserId, model.userId);
            
            if ([_currentUserId isEqualToString:model.userId]) {
                [menu setMenuItems:@[deleteItem]];
            } else {
                [menu setMenuItems:@[replyItem]];
            }
            
            [menu setMenuVisible:YES animated:YES];
        }
    }
}

/**
 *  删除评论
 */
- (void)deleteCurrentComment:(UIMenuItem *)deleteItem
{
    JSTDynamicDetailsCommentModel *model = [_commentData safeObjectAtIndex:_longPressIndexPath.section];
    [JSTNewServer requestDeleteComment:model.commentId success:^(NSDictionary *dataDic) {
        
    } error:^(NSString *errStr) {
        
    }];
}

/**
 *  回复评论
 */
- (void)replyCurrentComment:(UIMenuItem *)replyItem
{
    if (![KYUserAccountTool shareUserData].token) {
        KYLoginController *loginVc = [[KYLoginController alloc] init];
        KYNavigationController *nav = [[KYNavigationController alloc] initWithRootViewController:loginVc];
        [self presentViewController:nav animated:YES completion:nil];
    } else {
        JSTDynamicDetailsCommentModel *model = [_commentData safeObjectAtIndex:_longPressIndexPath.section];
        JSTPublishViewController *publishViewController = [[JSTPublishViewController alloc] init];
        publishViewController.dynamicId = _dataModel.dynamicId;
        publishViewController.personId = model.userId;
        publishViewController.personName = model.userNick;
        [self.navigationController pushViewController:publishViewController animated:YES];
    }
}

#pragma mark - JSTCommentCellDelegate方法
- (void)changePersonPage:(NSString *)personId
{
    JSTUserInfoViewController *userInfoViewController = [[JSTUserInfoViewController alloc] init];
    userInfoViewController.userId = personId;
    [self.navigationController pushViewController:userInfoViewController animated:YES];
}

#pragma mark - JSTCommonHeaderViewDelegate
- (void)rightChange
{
    _isComment = NO;
    if (_praiseData.count == 0) {
        _listFaildView.frame = CGRectMake(0, CGRectGetMaxY(self.headerView.frame) + kCurrentScreenWidth(30), kScreenWidth, kCurrentScreenWidth(150));
        self.faildImageView.image = [UIImage imageNamed:@"state_Thumbup_bg"];
        _listFaildView.hidden = NO;
    } else {
        _listFaildView.hidden = YES;
    }
    [self.tabView reloadData];
}

- (void)leftChange
{
    _isComment = YES;
    if (_commentData.count == 0) {
        _listFaildView.frame = CGRectMake(0, CGRectGetMaxY(self.headerView.frame) + kCurrentScreenWidth(30), kScreenWidth, kCurrentScreenWidth(150));
        self.faildImageView.image = [UIImage imageNamed:@"state_comments_bg"];
        _listFaildView.hidden = NO;
    } else {
        _listFaildView.hidden = YES;
    }
    [self.tabView reloadData];
}

- (void)changePersonPage
{
    JSTUserInfoViewController *userInfoViewController = [[JSTUserInfoViewController alloc] init];
    userInfoViewController.userId = _dataModel.userId;
    [self.navigationController pushViewController:userInfoViewController animated:YES];
}

#pragma mark - JSTCommentFootViewDelegate
- (void)onClickFoot:(NSInteger)tag
{
    switch(tag) {
        case 100: // 分享
        {
            [self onClickSocial:@[_dataModel.contentText]];
        }
            break;
        case 101: // 评论
        {
            [self commentCurrentStatus];
            
        }
            break;
        case 102: // 点赞
        {
            [self likeBtnClick:tag];
        }
            break;
            
        default:
            break;
    }
}

/**
 *  分享
 *
 *  @param activityItems 分享的内容
 */
- (void)onClickSocial:(NSArray *)activityItems
{
    // 服务类型控制器
    UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
    [self presentViewController:activityViewController animated:YES completion:nil];
    
    // 选中分享类型
    [activityViewController setCompletionWithItemsHandler:^(NSString * __nullable activityType, BOOL completed, NSArray * __nullable returnedItems, NSError * __nullable activityError) {
        // 显示选中的分享类型
        KYLog(@"actType %@",activityType);
         
        if (completed) {
            KYLog(@"ok");
        } else {
            KYLog(@"no ok");
        }
    }];
}

/**
 *  评论
 */
- (void)commentCurrentStatus
{
    if (![KYUserAccountTool shareUserData].token) {
        KYLoginController *loginVc = [[KYLoginController alloc] init];
        KYNavigationController *nav = [[KYNavigationController alloc] initWithRootViewController:loginVc];
        [self presentViewController:nav animated:YES completion:nil];
    } else {
        JSTPublishViewController *publishViewController = [[JSTPublishViewController alloc] init];
        publishViewController.dynamicId = _dataModel.dynamicId;
        KYNavigationController *nav = [[KYNavigationController alloc] initWithRootViewController:publishViewController];
        [self presentViewController:nav animated:YES completion:nil];
    }
}

/**
 *  点赞
 */
- (void)likeBtnClick:(NSInteger)tag
{
    if (![KYUserAccountTool shareUserData].token) {
        KYLoginController *loginVc = [[KYLoginController alloc] init];
        KYNavigationController *nav = [[KYNavigationController alloc] initWithRootViewController:loginVc];
        [self presentViewController:nav animated:YES completion:nil];
    } else {
        // 0.点赞即触发请求
        [JSTNewServer requestFabulous:_dataModel.dynamicId success:^(NSDictionary *dataDic) {
            [self setUpCommentData];
        } error:^(NSString *errStr) {
            
        }];
        
        // 1.更改按钮状态
        UIButton *btn = (UIButton *)[self.footerVeiw viewWithTag:tag];
        btn.selected = !btn.selected;
    }
}

#pragma mark - 懒加载子控件
- (UITableView *)tabView
{
    if (!_tabView)
    {
        _tabView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 49) style:UITableViewStylePlain];
        _tabView.delegate = self;
        _tabView.dataSource = self;
        [_tabView addHeaderWithTarget:self action:@selector(setUpCommentData)];
        _tabView.tableFooterView = [[UIView alloc] init];
    }
    return _tabView;
}

- (JSTCommonHeaderView *)headerView
{
    if (!_headerView)
    {
        _headerView = [[JSTCommonHeaderView alloc] init];
        _headerView.delegate = self;
    }
    return _headerView;
}

- (JSTCommentFootView *)footerVeiw
{
    if (!_footerVeiw)
    {
        _footerVeiw = [[JSTCommentFootView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 49, kScreenWidth, 49)];
        _footerVeiw.backgroundColor = [UIColor whiteColor];
        _footerVeiw.delegate = self;
    }
    return _footerVeiw;
}

- (JSTCommonCenterView *)inPutBar
{
    if (!_inPutBar)
    {
        _inPutBar = [[JSTCommonCenterView alloc] init];
    }
    return _inPutBar;
}

- (UIView *)listFaildView
{
    if (!_listFaildView)
    {
        _listFaildView = [[UIView alloc] init];
        _faildImageView = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth - kCurrentScreenWidth(175))/2, kCurrentScreenWidth(10), kCurrentScreenWidth(175), kCurrentScreenWidth(143))];
        [_listFaildView addSubview:_faildImageView];
    }
    return _listFaildView;
}
@end
